<template>
  <ContentCard>
    <div class="approval-details">
      <PageHeaderNew title="审批详情" :breadCrumb="breadCrumb" showBack />
      <div class="details">
        <div class="details-ctl">
          <div class="ctl-item" v-for="item in ctlFormList" :key="item.id">
            <div class="info-card" v-if="item.subCode">
              <div class="sub-name">{{ item.cnName }}</div>
              <div class="sub">
                <RenderingForm
                  :set-up-list="item.approvalCtlValueDetailList"
                  :layout="rest"
                  :regex="regex"
                  :field-names="{
                    labelName: 'cnName',
                    componentType: 'componentType'
                  }"
                  ref="renderFormRef"
                />
              </div>
              <!-- <a-divider /> -->
            </div>

            <template v-else>
              <RenderingForm
                :set-up-list="[item]"
                :layout="rest"
                :review="true"
                :regex="regex"
                :field-names="{
                  labelName: 'cnName',
                  componentType: 'componentType'
                }"
                ref="renderFormRef"
              />
              <a-divider />
            </template>
          </div>
        </div>
        <div class="details-process">
          <div class="process-info">
            <div class="title">
              <div class="release-user-info">
                <div>编号：{{ currentApprovalInfo.approvalCode }}</div>
              </div>
              <h3>{{ currentApprovalInfo.approvalTitle }}</h3>
              <!-- <div>{{ currentApprovalInfo.currentApprovalResult }}</div> -->
            </div>
            <a-steps :current="current" direction="vertical">
              <template v-for="item in approvalPointList" :key="item.id">
                <a-step v-if="item.pointType !== 6">
                  <template #icon>
                    <icon-send
                      v-if="item.pointType === 2 || item.pointType === 5"
                    />
                    <icon-stamp v-if="item.pointType === 1" />
                  </template>
                  <a-space>
                    {{ item.pointName }}
                    <a-tag :color="item.pointRate === 1 ? 'green' : ''">
                      <template #icon>
                        <icon-check-circle-fill />
                      </template>
                      {{ getProcessRateByNumber(item.pointRate) }}
                    </a-tag>
                    <a-tooltip
                      content="加签"
                      v-if="[4, 5].includes(item.pointRate)"
                    >
                      <a-button
                        type="primary"
                        @click="addNodeBefore(item)"
                        size="mini"
                      >
                        <template #icon>
                          <icon-plus />
                        </template>
                      </a-button>
                    </a-tooltip>
                  </a-space>
                  <div
                    class="user-details"
                    v-for="user in item.participantInfos"
                    :key="user.id"
                  >
                    <div class="user-info" v-if="item.pointType === 100">
                      <div class="user-name" style="width: 100%">
                        {{ item.remark }}
                      </div>
                    </div>
                    <div class="user-info" v-else>
                      <div class="user-name" style="width: 100%">
                        <!-- {{ getPointTypeByNumber(item.pointType) }} -->
                      </div>
                      <div>
                        {{ user.objName }}
                        <a-tag
                          :color="user.approvalResult === 1 ? 'green' : ''"
                        >
                          <template #icon>
                            <icon-check-circle-fill />
                          </template>
                          {{ getProcessRateByNumber(user.approvalResult) }}
                        </a-tag>
                      </div>
                      <div>提交时间：</div>
                      <div>审批意见：</div>
                      <div
                        v-if="user.opinions && item.pointType === 1"
                        class="opinions"
                      >
                        {{ user.opinions }}
                      </div>
                    </div>
                  </div>
                  <!-- <template #description>
                  <div v-for="i in 10">节点类型{{ item.pointType }}</div>
                </template> -->
                </a-step>
              </template>
            </a-steps>
          </div>
          <!-- :TODO:当前审批人可见，其余不可见  -->
          <div class="drawer-footer">
            <a-space class="drawer-footer-operator">
              <!-- <IconText :icon="'icon-edit'" :text="'修改'" /> -->
              <IconText @click="revoke" :icon="'icon-undo'" :text="'撤销'" />
              <!-- <IconText :icon="'icon-message'" :text="'评论'" /> -->
            </a-space>
            <a-space v-if="!currentApprovalInfo.approvalIsEnd">
              <!-- 如果是首个审批人，不显示退回按钮 TODO:-->
              <a-button type="outline" @click="showOpinionsModal(2)"
                >退回</a-button
              >
              <a-button @click="showOpinionsModal(3)">拒绝</a-button>
              <a-button type="primary" @click="showOpinionsModal(1)"
                >同意</a-button
              >
            </a-space>
          </div>
        </div>
      </div>
    </div>
  </ContentCard>
  <ApprovalOpinionsModal
    v-model:visible="opinionsModalVisible"
    v-model:backNodeId="approvalData.detail.backNodeId"
    :opinions="approvalData.detail.participants.opinions"
    @submit="approvalEvent"
    :approverList="approverList"
    :approvalType="approvalType"
  />
  <AddNodeModal
    v-model:visible="addNodeVisible"
    v-model:addNodeData="addNodeData"
    @submit="addNode"
  />
</template>

<script setup lang="ts">
import IconText from '@/components/IconText.vue';
import {
  getApprovalReleaseByApprovalCode,
  editApprovalRelease,
  delApprovalRelease
} from '@/apis/approvalExecute';
import { getPointTypeByNumber, getProcessRateByNumber } from '@/utils/approval';
import type {
  EditApprovalRelease,
  DelApprovalRelease,
  PointDetail
} from '@/apis/approvalExecute/type';
import ApprovalOpinionsModal from './conponents/ApprovalOpinionsModal.vue';
import type {
  ApprovalParams,
  CurrentApprovalInfo
} from '@/apis/approvalExecute/repType';
import { getApprovalPoint, getApprovalPointIds } from '@/utils/approval';
import { useRoute } from 'vue-router';
import { onMounted } from 'vue';
import { addApprovalNode } from '@/apis/approvalExecute/index';
import type { AddNode } from '@/apis/approvalExecute/addNodeType';
import AddNodeModal from './conponents/AddNodeModal.vue';
import RenderingForm from '@/components/DyForms/DynamicForms/RenderingForm/Form/index.vue';
import regex from '@/utils/regex';
import useControlFormStore from '@/store/controlForm';
const controlFormStore = useControlFormStore();
controlFormStore.fieldNames.labelName = 'cnName';

const rest = ref('horizontal');
const route = useRoute();
const breadCrumb = ['我的审批', '审批详情'];
const init = () => {
  approvalInfo.value.approvalCode = route.query.approvalCode;
};
onMounted(() => {
  init();
  getApprovalDetail();
});
const approvalInfo = ref<ApprovalParams>({});
const currentApprovalInfo = ref<CurrentApprovalInfo>({});
const ctlFormList = ref<any[]>([]);
// 获取审批详情
const getApprovalDetail = async () => {
  if (!approvalInfo.value.approvalCode) return;
  const res = await getApprovalReleaseByApprovalCode(
    approvalInfo.value.approvalCode
  );
  approvalInfo.value = res?.repoSingleApprovalParam?.approvalInfo || {};
  currentApprovalInfo.value =
    res?.repoSingleApprovalParam?.currentApprovalInfo || {};
  const { approvalCtlValueDetailList, approvalSubsetDetailList } =
    approvalInfo.value.approvalFormDetail;
  approvalCtlValueDetailList?.forEach((item) => {
    item.ctlValue = item.ctlValue?.length ? JSON.parse(item.ctlValue) : void 0;
    item.values = item.ctlValue;
    item.props = JSON.parse(item.props);
  });
  approvalSubsetDetailList?.forEach((item) => {
    item?.approvalCtlValueDetailList?.forEach((ctl) => {
      ctl.ctlValue = ctl.ctlValue?.length ? JSON.parse(ctl.ctlValue) : void 0;
      ctl.values = ctl.ctlValue;
      ctl.props = JSON.parse(ctl.props);
    });
  });
  ctlFormList.value = [
    ...(approvalCtlValueDetailList || []),
    ...(approvalSubsetDetailList || [])
  ];
  ctlFormList.value.sort((a, b) => a.orderNo - b.orderNo);
  console.log('ctlFormList.value', ctlFormList.value);

  getFormData();
  //查找发起人节点，组成审批线路
  approvalPointList.value = [];
  const initiator = approvalInfo.value.pointDetails?.find(
    (item) => item.pointType === 5
  );
  approvalLine(initiator);
};
const current = computed(() => {
  const index = approvalPointList.value.findIndex(
    (item) => item.isCurrentPoint
  );
  return index + 1;
});
const approvalData = reactive<{ detail: EditApprovalRelease }>({
  detail: { participants: { opinions: '' } }
});
// 审批信息
const getFormData = () => {
  // 解构接口对象组装审批需要的信息
  const { appCode, approvalCode } = approvalInfo.value;
  const { processId, pointType, examineType, nodeDetailId } =
    currentApprovalInfo.value;
  const { objId, pointValueId, orderNo, approvalResult, objName } =
    currentApprovalInfo.value.participants[0];
  approvalData.detail = {
    appCode,
    approvalCode,
    examineType,
    processId,
    nodeType: pointType,
    nodeDetailId,
    participants: { objId, pointValueId, orderNo, approvalResult: 1, objName }
  };
};
const approvalEvent = async (opinions: string) => {
  approvalData.detail.participants.opinions = opinions;
  const { nodeDetailId, backNodeId } = approvalData.detail;
  const { pointDetails } = approvalInfo.value;
  // 如果backNodeId存在，说明是退回事件
  if (backNodeId && pointDetails) {
    //获取当前节点到退回至节点的区间审核节点id
    const ids = getApprovalPointIds(backNodeId, pointDetails);
    approvalData.detail.backIntervalNodeIds = ids;
  }
  // console.log('approvalData.detail', approvalData.detail);

  await editApprovalRelease(approvalData.detail);
  getApprovalDetail();
};
const revokeParams = reactive<DelApprovalRelease>({});
//审批动作
const revoke = async () => {
  // opinionsModalVisible.value = true;
  const { appCode, approvalCode } = approvalInfo.value;
  revokeParams.appCode = appCode;
  revokeParams.approvalCode = approvalCode;
  await delApprovalRelease(revokeParams);
};
const opinionsModalVisible = ref(false);
const approvalType = ref(0); // 审批类型
/**
 *
 * @param approvalResult 审批结果 1同意2退回3拒绝
 */
const showOpinionsModal = (approvalResult: number) => {
  approvalType.value = approvalResult;
  opinionsModalVisible.value = true;
  approvalData.detail.participants.approvalResult = approvalResult;
  //不是退回事件，把退回至审核人列表设为空
  if (approvalResult !== 2) approverList.value = [];
  else {
    const { pointDetails } = approvalInfo.value;
    if (typeof pointDetails !== 'object') approverList.value = [];
    let approver = getApprovalPoint(pointDetails);
    approverList.value = approver;
    if (approver.length < 2) approverList.value = [];
    //审批结束
    if (approver.approvalInfo.processRate === 4) {
      //TODO:审批结束，1审批通过2审批拒绝
      // 审批结束后续。。。
      // 入职审批结束
      // 离职审批结束
      // 转正审批结束
    }
  }
};

const approverList = ref(); // 审核人之前的审核人列表，用于退回至事件

const addNodeVisible = ref(false);
const addNodeData = ref<AddNode>({
  approvalId: 0,
  approvalCode: '',
  currentApprovalNodeId: 0,
  currentApprovalUserId: 0,
  currentApprovalUserName: '',
  approvalOpinions: '',
  pointDetail: {
    // approvalCode: '',
    nextStep: 0,
    nextStepType: 0,
    previousStep: 0,
    previousStepType: 0,
    processId: 0,
    pointName: '审核人',
    pointType: 1,
    examineType: 0,
    participantInfos: []
  }
});
const operateId = ref(0);
const addNodeBefore = (currentNode: PointDetail) => {
  addNodeVisible.value = true;
  operateId.value = Number(currentNode.id);
};
/**
 * 加签
 */
const addNode = async () => {
  //找到当前审批中节点pointRate=4,及上下节点
  const {
    id: approvalId,
    processId,
    approvalCode,
    pointDetails
  } = approvalInfo.value;
  if (!pointDetails?.length) throw '审批节点长度不能为0';
  //审批中节点下标
  const index = pointDetails.findIndex((item) => item.pointRate === 4);
  const currentNode = pointDetails[index];
  //加签节点下标
  const addNodeIndex = pointDetails.findIndex(
    (item) => item.id === operateId.value
  );

  const preNode = pointDetails[addNodeIndex];
  const nextNode = pointDetails[addNodeIndex + 1];

  const { id: currentApprovalNodeId, participantInfos } = currentNode;
  //当前审批中的人
  if (!participantInfos?.length) {
    throw '审批人数据长度不能为0';
  }
  const currentIndex = participantInfos.findIndex(
    (item) => item.approvalResult === 4
  );
  const currentParticipant = participantInfos[currentIndex];
  const { objId: currentApprovalUserId, objName: currentApprovalUserName } =
    currentParticipant;
  const { id: nextStep, pointType: nextStepType } = nextNode;
  const { id: previousStep, pointType: previousStepType } = preNode;
  // 本节点审批的信息
  addNodeData.value.approvalId = approvalId;
  addNodeData.value.approvalCode = approvalCode;
  addNodeData.value.currentApprovalNodeId = currentApprovalNodeId;
  addNodeData.value.currentApprovalUserId = currentApprovalUserId;
  addNodeData.value.currentApprovalUserName = currentApprovalUserName;
  // 新增的节点信息
  addNodeData.value.pointDetail.previousStep = previousStep;
  addNodeData.value.pointDetail.previousStepType = previousStepType;
  addNodeData.value.pointDetail.nextStep = nextStep;
  addNodeData.value.pointDetail.nextStepType = nextStepType;

  console.log('approvalInfo.value', addNodeData.value);

  await addApprovalNode(addNodeData.value);
  getApprovalDetail();
};
/**
 * 审批线路数据
 */
const approvalPointList = ref<PointDetail[]>([]);
/**
 * 根据节点的下一个节点得到一个串
 */
const approvalLine = (ponit?: PointDetail) => {
  if (!ponit) return;
  approvalPointList.value.push(ponit);
  const { nextStep } = ponit;
  const nextNode = approvalInfo.value.pointDetails?.find(
    (item) => item.id === nextStep
  );
  approvalLine(nextNode);
};
</script>

<style lang="less" scoped>
.approval-details {
  height: calc(100vh - 135px); //40 32 60
  //   overflow: auto;
  display: flex;
  flex-direction: column;
  .details {
    flex: 1;
    display: flex;
    padding: 16px 0;
    overflow: hidden;
    &-ctl {
      flex: 1;
      margin-right: 16px;
      padding-right: 16px;
      overflow: auto;
      height: 100%;
      .ctl-item {
        // display: flex;
        // align-items: center;
        margin-bottom: 16px;
        width: 100%;
        .info-card {
          // border: 1px solid #eee;
        }
        .sub-item {
          display: flex;
          align-items: center;
          width: 100%;
          // padding: 0 16px;
          margin: 16px 0;
          .ctl-title {
            min-height: 16px;
            margin-right: 16px;
          }
          .ctl-value {
            flex: 1;
            padding: 8px;
            border: 1px solid #eee;
            border-radius: 5px;
          }
        }
      }
    }
    &-process {
      //   height: 100%;
      //   overflow: auto;
      border-radius: 5px;

      border: 1px solid #eee;
      display: flex;
      flex-direction: column;
      .process-info {
        flex: 1;
        overflow: auto;
        padding: 10px 16px;
        .user-details {
          width: 300px;
          background: #f9f9f9;
          padding: 3px 6px;
          border-radius: 5px;
        }
      }
      .drawer-footer {
        border-top: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        padding: 3px 6px;
        .drawer-footer-operator {
          width: 100%;
          justify-content: space-around;
        }
      }
    }
  }
}
.opinions {
  border: 1px #eee dashed;
  border-radius: 5px;
  padding: 0 16px;
  color: #747474;
  font-size: 12px;
}
/* 定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸 */
::-webkit-scrollbar {
  z-index: 100;
  width: 6px;
  height: 6px;
  background-color: #fff;
}

// /* 定义滚动条轨道 内阴影+圆角 */
::-webkit-scrollbar-track {
  z-index: 100;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgb(144 147 153 / 30%);
}

// /* 定义滑块 内阴影+圆角 */
::-webkit-scrollbar-thumb {
  z-index: 100;
  background-color: rgb(169 169 169 / 50%);
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgb(144 147 153 / 30%);
}
.sub {
  // width: 100%;
  padding: 0px 20px;
}
.sub-name {
  height: 36px;
  border-radius: 4px;
  line-height: 36px;
  font-weight: 700;
  background: #edeffd;
  padding: 5px 16px;
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  &::before {
    position: relative;
    // top: 38px;
    // left: 10px;
    display: inline-block;
    height: 20px;
    width: 5px;
    margin-right: 10px;
    border-radius: 2px;
    content: '';
    background-color: #165dff;
  }
}
</style>
